package com.bdqn.web; /**
 * <h3>项目名称:demo02222</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-03 13:38</p>
 **/

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/*
*2.用注解方式配置servlet
*起到描述说明的作用。
* */
@WebServlet(name = "MyServlet",
        initParams = {@WebInitParam(name = "encoding",value = "utf-8")},
        /*value = "/MyServlet",*/urlPatterns = {"*.do"},
        loadOnStartup = 1)
public class MyServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        //获取初始化参数
        String encoding = config.getInitParameter("encoding");
        //init方法仅执行一次
        System.out.println("调用了init方法。。。初始化参数encoding:"+encoding);
    }

    //destroy方法在对象销毁时调用的
    @Override
    public void destroy() {
        System.out.println("调用了destroy方法。。。");
    }

    //接收并处理用户的请求，并做出响应
    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        System.out.println("调用了service方法。。。");
        //处理请求和响应中的乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");//设置响应内容的类型
        //接收用户传来的参数
        String key = request.getParameter("key");
        //将参数拼接后写到浏览器端
        PrintWriter writer = response.getWriter();
        String html="<p style='color:red;font-weight:bold;'>"+
                "服务器端收到了："+key+"</p>";
        //向浏览器端写回一些数据
        writer.write(html);

    }

    /*
    有了上面的方法，这两个方法就用不上了
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }*/
}
